﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Extentions;
using TrainingReminderSystem.Model;
using TrainingReminderSystem.Dal;
using System.Threading.Tasks;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 客户机构培训记录 逻辑层
    /// </summary>
    public partial class SysCustomerOrganizationTrainBll : PcLoginedBll
    {
        #region 添加和编辑的时候 验证数据和设置默认值
        
        /// <summary>
        /// 添加和编辑的时候 验证数据和设置默认值
        /// </summary>
        /// <param name="model"></param>
        /// <param name="isAdd">添加还是编辑,可以不管此参数</param>/// <param name="db"></param>
        /// <returns>是否通过,true表示验证通过,false代表验证没有通过</returns>
        public AjaxResult<dynamic> Validate(SysCustomerOrganizationTrain model, bool isAdd, DbEntities db)
        {
            var r = new AjaxResult<dynamic>();
            if (model == null)
            {
                r.Message = LanguageHelper.NoSubmitData;
                return r;
            }
            model.ExTrimProperty();
            r = ValidatePartial(model, isAdd, r, db);
            if (r.Success == false) return r;
            r.Success = false;
            
            
            if (isAdd) {
                model.CreateSysEmployeeID = CurrentEmployee?.SysEmployeeID;
                model.CreateDate = DateTime.Now;
            }
            
            r.Success = true;
            return r;
        }
        
        #endregion
        
        #region 保存数据
        
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Save(SysCustomerOrganizationTrain model)
        {
            using (var db = Db)
            {
                return await Save(model, db);
            }
        }
        
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的model对象的主键能得到对象</param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Save(SysCustomerOrganizationTrain model, DbEntities db)
        {
            if (this.SaveJudgePartial(model, db))
            {
                return await Add(model, db);
            }
            return await Modify(model, db);
        }
        
        #endregion
        
        #region 分页方法
        
        /// <summary>
        /// 查询条件,能替换掉一些属性查询为自定义查询
        /// </summary>
        /// <param name="where"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private Expression<Func<SysCustomerOrganizationTrain, bool>> InitSearchDelegete(Expression<Func<SysCustomerOrganizationTrain, bool>> where, string key, string val, DbEntities db)
        {
            var r = InitSearchDelegetePartial(where, key, val, db);
            if (r != null) return r;
            return null;
        }
        
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="form"></param>
        /// <param name="sortField"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public async Task<AjaxResult<List<SysCustomerOrganizationTrainExList>>> GetListByPage(int index, int size, IFormCollection form = null, string sortField = "", bool asc = false)
        {
            using (var db = Db)
            {
                using var tran = db.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                
                Expression<Func<SysCustomerOrganizationTrain, bool>> where = InitSearch<SysCustomerOrganizationTrain, DbEntities>(form, InitSearchDelegete, db); //拼接查询条件方法
                IQueryable<SysCustomerOrganizationTrain> query = OrderByPartial(db.SysCustomerOrganizationTrain, sortField, asc, db);
                int counts;
                var tempIDList = query.ExGetListByPage(index, size, out counts, where).Select(m => m.ID);
                var r = new AjaxResult<List<SysCustomerOrganizationTrainExList>>();
                r.Total = counts;
                IQueryable<SysCustomerOrganizationTrain> list = query.AsNoTracking().Where(m => tempIDList.Contains(m.ID));
                var tempList = list.Select(m => new SysCustomerOrganizationTrainExList()
                {
                    ID = m.ID,
                    SysCustomerID = m.SysCustomerID,
                    SysCustomer = new SysCustomerExPart(){
                        SysCustomerID = m.SysCustomer.SysCustomerID,
                        EnumSysCustomerType = m.SysCustomer.EnumSysCustomerType,
                        SysCustomerName = m.SysCustomer.SysCustomerName,
                        Phone = DbFun.fn_replaceNum(m.SysCustomer.Phone, CanSeePhone),
                        EnumStatus = m.SysCustomer.EnumStatus,
                        EnumSysCustomerSource = m.SysCustomer.EnumSysCustomerSource,
                        EnumSysCustomerIntention = m.SysCustomer.EnumSysCustomerIntention,
                        EnumGender = m.SysCustomer.EnumGender,
                        Qualification = m.SysCustomer.Qualification
                    },
                    OrganizationID = m.OrganizationID,
                    Organization = new OrganizationExPart(){
                        OrganizationID = m.Organization.OrganizationID,
                        Name = m.Organization.Name,
                        Phone = DbFun.fn_replaceNum(m.Organization.Phone, CanSeePhone),
                        EnumStatus = m.Organization.EnumStatus
                    },
                    TrainDateTimeStart = m.TrainDateTimeStart,
                    TrainDateTimeEnd = m.TrainDateTimeEnd,
                    TrainContent = m.TrainContent,
                    IsDel = m.IsDel,
                    CreateSysEmployeeID = m.CreateSysEmployeeID,
                    CreateDate = m.CreateDate,
                    Remark = m.Remark
                });
                var resultList = await tempList.ToListAsync();
                return GetListByPagePartial(resultList, r, db);
            }
        }
        
        #endregion
        
        #region 得到单对象,返回值有可能为null
        
        /// <summary>
        /// 得到单对象,返回值有可能为null
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<AjaxResult<SysCustomerOrganizationTrain>> GetModel(int id)
        {
            using (var db = Db)
            {
                return await GetModel(id, db);
            }
        }
        
        internal async Task<AjaxResult<SysCustomerOrganizationTrain>> GetModel(int id, DbEntities db)
        {
            string include = GetModelIncludePartial();
            IQueryable<SysCustomerOrganizationTrain> query = !string.IsNullOrWhiteSpace(include) ? db.SysCustomerOrganizationTrain.Include(include) : db.SysCustomerOrganizationTrain;
            var temp = query.AsNoTracking().Where(m => m.ID == id);
            var dbModel = await temp.FirstOrDefaultAsync();
            return GetModelReturnPartial(dbModel, db);
        }
        
        #endregion
        
        #region 添加数据
        
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Add(SysCustomerOrganizationTrain model)
        {
            using (var db = Db)
            {
                return await Add(model, db);
            }
        }
        
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Add(SysCustomerOrganizationTrain model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, true, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                db.SysCustomerOrganizationTrain.Add(model);
                string error = AddLog(db, model, EnumLogType.新建);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, true, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = model;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }
        
        #endregion
        
        #region 编辑Old
        
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Update(SysCustomerOrganizationTrain model)
        {
            using (var db = Db)
            {
                return await Update(model, db);
            }
        }
        
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Update(SysCustomerOrganizationTrain model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, false, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                var dbModel = await db.SysCustomerOrganizationTrain.FirstOrDefaultAsync(m => m.ID == model.ID);
                if (dbModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }
                
                dbModel.SysCustomerID = model.SysCustomerID;
                dbModel.OrganizationID = model.OrganizationID;
                dbModel.TrainDateTimeStart = model.TrainDateTimeStart;
                dbModel.TrainDateTimeEnd = model.TrainDateTimeEnd;
                dbModel.TrainContent = model.TrainContent;
                dbModel.Remark = model.Remark;
                
                string error = AddLog(db, model, EnumLogType.编辑);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, false, r, db, dbModel);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = dbModel;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }
        
        #endregion
        
        #region 编辑New
        
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Modify(SysCustomerOrganizationTrain model)
        {
            using (var db = Db)
            {
                return await Modify(model, db);
            }
        }
        
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的主键能得到对象</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Modify(SysCustomerOrganizationTrain model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(model, false, db);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                ModifyBasePartial(model, db, typeof(SysCustomerOrganizationTrainExPost));
                
                string error = AddLog(db, model, EnumLogType.编辑);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = AddUpdateSuccessPartial(model, false, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                r.Result = model;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }
        
        #endregion
        
        #region 删除
        
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AjaxResult<dynamic>> Del(int id)
        {
            using (var db = Db)
            {
                return await Del(id, db);
            }
        }
        
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal async Task<AjaxResult<dynamic>> Del(int id, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = await db.Database.BeginTransactionAsync();
            try
            {
                var dbModel = await db.SysCustomerOrganizationTrain.FirstOrDefaultAsync(m => m.ID == id);
                if (dbModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }
        
                r = DelValidatePartial(dbModel, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                dbModel.IsDel = true;//db.SysCustomerOrganizationTrain.Remove(dbModel);
                string error = AddLog(db, dbModel, EnumLogType.删除);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                await db.SaveChangesAsync();
                r = DelSuccessPartial(dbModel, r, db);
                if (r.Success == false)
                {
                    return r;
                }
                await db.SaveChangesAsync();
                if (hasTran == false)
                {
                    await tran.CommitAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
                r.Success = true;
                r.Message = LanguageHelper.Success;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    await tran.RollbackAsync();
                    await tran.DisposeAsync();
                    tran = null;
                }
            }
        }
        
        #endregion
            
        #region 下拉选择
        
        /// <summary>
        /// 下拉选择
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        public async Task<AjaxResult<List<SysCustomerOrganizationTrain>>> GetListSelect(IFormCollection form = null)
        {
            using (var db = Db)
            {
                using var tran = db.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                
                Expression<Func<SysCustomerOrganizationTrain, bool>> where = InitSearch<SysCustomerOrganizationTrain, DbEntities>(form, InitSearchDelegete, db); //拼接查询条件方法
                var selectID = form["selectIDName"].ExTrim();
                var obj = db.SysCustomerOrganizationTrain.AsNoTracking();
                bool hasSelectID = false;
                if (!string.IsNullOrEmpty(selectID))
                {
                    if (selectID.IndexOf(',') != -1)
                    {
                        var selectIDList = selectID.ExToSplitList(',', false);
                        if (selectIDList.Count > 0)
                        {
                            hasSelectID = true;
                            obj = obj.OrderByDescending(m => selectIDList.Contains(m.ID)).ThenByDescending(m => m.ID);
                        }
                    }
                    else
                    {
                        var selectIDInt = selectID.ExToInt32();
                        if (selectIDInt > 0)
                        {
                            hasSelectID = true;
                            obj = obj.OrderByDescending(m => selectIDInt == m.ID).ThenByDescending(m => m.ID);
                        }
                    }
                    if (hasSelectID == false)
                    {
                        obj = obj.OrderByDescending(m => m.ID);
                        where = where.ExAnd(m => m.TrainContent.Contains(selectID));
                    }
                }
                if (hasSelectID == false)
                {
                    obj = obj.OrderByDescending(m => m.ID);
                    //where = where.ExAnd(m => m.EnumStatus == EnumStatus.启用);
                }
                var result = new AjaxResult<List<SysCustomerOrganizationTrain>>() { Success = true };
                IQueryable<SysCustomerOrganizationTrain> list = obj.Where(where).Take(DefaultSize);
                var tempList = list.Select(m => new SysCustomerOrganizationTrain()
                {
                    
                });
                result.Result = await tempList.ToListAsync();
                return result;
            }
        }
        
        #endregion
        
        //#region 导入
        //#endregion
    }
}
